package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/updateAdminPassword")
public class UpdateAdminPasswordServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前登录的管理员
        HttpSession session = request.getSession(false);
        if (session == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            out.print(gson.toJson(result));
            return;
        }
        
        // 从session中获取当前登录的管理员信息
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null || currentUser.getRole() != 2) {
            result.put("success", false);
            result.put("message", "请先登录系统管理员账号");
            out.print(gson.toJson(result));
            return;
        }
       
        // 获取真正的管理员ID（从session的adminId属性中获取，而不是从User对象的ID）
        String adminId = (String) session.getAttribute("adminId");
        if (adminId == null) {
            result.put("success", false);
            result.put("message", "管理员会话信息异常，请重新登录");
            out.print(gson.toJson(result));
            return;
        }
        
        System.out.println("UpdateAdminPasswordServlet - 从session获取的adminId: " + adminId);
        System.out.println("UpdateAdminPasswordServlet - 管理员信息: " + currentUser);
        

        
        try {
            // 读取请求体中的JSON数据
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            // 解析JSON数据
            JsonObject jsonObject = gson.fromJson(sb.toString(), JsonObject.class);
            String oldPassword = jsonObject.get("oldPassword").getAsString();
            String newPassword = jsonObject.get("newPassword").getAsString();
            String confirmPassword = jsonObject.get("confirmPassword").getAsString();
            
            System.out.println("UpdateAdminPasswordServlet - 旧密码: " + oldPassword);
            System.out.println("UpdateAdminPasswordServlet - 新密码: " + newPassword);
            
            // 验证新密码和确认密码是否一致
            if (!newPassword.equals(confirmPassword)) {
                result.put("success", false);
                result.put("message", "新密码和确认密码不一致");
                out.print(gson.toJson(result));
                return;
            }
            
            // 调用服务更新密码
            result = userService.updateAdminPassword(adminId, oldPassword, newPassword);
            System.out.println("UpdateAdminPasswordServlet - 更新结果: " + result);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "密码更新失败: " + e.getMessage());
        }
        
        out.print(gson.toJson(result));
    }
}
